<?php

namespace backend\controllers;

use Yii;
use yii\web\Response;
use yii\JPush\Client;
use ServerAPI;
use yii\data\Pagination;
use backend\models\User;
use backend\models\ZhiboList;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * UserController implements the CRUD actions for User model.
 */
class UserController extends BaseController
{
	public $layout = "lte_main";

    /**
     * Lists all User models.
     * @return mixed
     */
    public function actionIndex()
    {


//        return $this->render('http://www.shierdao.net/html/tixian.php', '111111');
//
//        var_dump(Yii::$app->request->get());

        $query = User::find();
         $querys = Yii::$app->request->get('query');
        $querys1 = Yii::$app->request->get('zhubo');
        $querys2 = Yii::$app->request->get('yonghu');
//        var_dump($querys1);
        if ($querys1) {
            $query = User::find()->where(['is_anchor' => $querys1]);
        }
        if ($querys2) {
            $query = User::find()->where(['is_anchor' => 0]);
        }


        if(count($querys) > 0){
            $condition = "";
            $parame = array();
            foreach($querys as $key=>$value){
                $value = trim($value);
                if(empty($value) == false){
                    $parame[":{$key}"]=$value;
                    if(empty($condition) == true){
                        $condition = " {$key}=:{$key} ";
                    }
                    else{
                        $condition = $condition . " AND {$key}=:{$key} ";
                    }
                }
            }
            if(count($parame) > 0){
                $query = $query->where($condition, $parame);
            }
        }

        $pagination = new Pagination([
            'totalCount' =>$query->count(), 
            'pageSize' => '20',
            'pageParam'=>'page', 
            'pageSizeParam'=>'per-page']
        );
        
        $orderby = Yii::$app->request->get('orderby', '');
        if(empty($orderby) == false){
            $query = $query->orderBy($orderby);
        }
        
        
        $models = $query
        ->offset($pagination->offset)
        ->limit($pagination->limit)
        ->all();
        return $this->render('index', [
            'models'=>$models,
            'pages'=>$pagination,
            'query'=>$querys,
        ]);
    }

    /**
     * Displays a single User model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);
        echo json_encode($model->getAttributes());

    }

    /**
     * Creates a new User model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new User();
        if ($model->load(Yii::$app->request->post())) {
        
              if(empty($model->start) == true){
                  $model->start = 10;
              }
              if(empty($model->status) == true){
                  $model->status = 10;
              }
        
            if($model->validate() == true && $model->save()){
                $msg = array('errno'=>0, 'msg'=>'保存成功');
                echo json_encode($msg);
            }
            else{
                $msg = array('errno'=>2, 'data'=>$model->getErrors());
                echo json_encode($msg);
            }
        } else {
            $msg = array('errno'=>2, 'msg'=>'数据出错');
            echo json_encode($msg);
        }
    }

    /**
     * Updates an existing User model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate()
    {
        $id = Yii::$app->request->post('ids');
        $type = Yii::$app->request->post('type');
        $model = $this->findModel($id);
        $userId = $model->user_id;
        $result1 = ZhiboList::find()->where(['user_id' => $userId])->asArray()->one();
        $cid = $result1['cid'];
        if ($type == 0) {
//            var_dump($model->user_id);die;
//            $model1 = ZhiboList::find()->where(['user_id' => $model->user_id])->asArray()->one();
            if ($model) {

                $p = new ServerAPI();

//                var_dump($result1['cid']);die;
                $result = $p->jinyongchannel($cid);
//                var_dump(Yii::$app->params['AppKey']);


                $model->is_jinbo = 0;
//                var_dump($model->save());die;

                if($model->validate() == true && $model->save()){

                    $client = new Client(Yii::$app->params['AppKey'],Yii::$app->params['MasterSecret']);

//                    var_dump($model->user_id);
                    $alias = strval($model->user_id);

//                    $client->device()->getAliasDevices(21003);
                    $response = $client->push();
                    $response->setPlatform('all');
//            $response->addTag(['tag1']);
                    $response   ->setNotificationAlert('Hello, JPush');
//        $response->addAllAudience();
                    $response->addAlias($alias);

                    $response    ->iosNotification('您的直播內容涉及黃色、暴力、違法等！請聯系管理員！', [
                        'sound' => 'sound',
                        'badge' => '+1',
                        'extras' => [
                            'type' => 0
                        ]
                    ]);

                    $response    ->androidNotification('您的直播內容涉及黃色、暴力、違法等！請聯系管理員！', [
                        'sound' => 'sound',
                        'badge' => '+1',
                        'extras' => [
                            'type' => 0
                        ]
                    ]);
                    try {
                        $response->send();
                    } catch (\JPush\Exceptions\JPushException $e) {
                        // try something else here
                        echo json_encode($e);
                    }


                    $msg = array('errno'=>0, 'msg'=>'保存成功11');
                    echo json_encode($msg);
                } else {
                    $msg = array('errno'=>2, 'data'=>$model->getErrors());
                    echo json_encode($msg);
                }
            } else {
                $msg = array('errno'=>2, 'msg'=>'数据出错');
                echo json_encode($msg);
            }

        } else {

            $p = new ServerAPI();

//                var_dump($result1['cid']);die;
            $result = $p->huifuchannel($cid);
//            var_dump($result);
            if ($model) {
                $model->is_jinbo = 1;
                if($model->validate() == true && $model->save()){


                    $client = new Client(Yii::$app->params['AppKey'],Yii::$app->params['MasterSecret']);

//                    var_dump($model->user_id);
                    $alias = strval($model->user_id);

//                    $client->device()->getAliasDevices(21003);
                    $response = $client->push();
                    $response->setPlatform('all');
//            $response->addTag(['tag1']);
                    $response   ->setNotificationAlert('Hello, JPush');
//        $response->addAllAudience();
                    $response->addAlias($alias);

                    $response    ->iosNotification('您可以開始直播了！', [
                        'sound' => 'sound',
                        'badge' => '+1',
                        'extras' => [
                            'type' => 1
                        ]
                    ]);

                    $response    ->androidNotification('您可以開始直播了！', [
                        'sound' => 'sound',
                        'badge' => '+1',
                        'extras' => [
                            'type' => 1
                        ]
                    ]);
                    try {
                        $response->send();
                    } catch (\JPush\Exceptions\JPushException $e) {
                        // try something else here
                        echo json_encode($e);
                    }



                    $msg = array('errno'=>0, 'msg'=>'保存成功');
                    echo json_encode($msg);
                }
                else{
                    $msg = array('errno'=>2, 'data'=>$model->getErrors());
                    echo json_encode($msg);
                }
            } else {
                $msg = array('errno'=>2, 'msg'=>'数据出错');
                echo json_encode($msg);
            }
        }

    }

    /**
     * Deletes an existing User model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete(array $ids)
    {
        if(count($ids) > 0){
            $c = User::deleteAll(['in', 'id', $ids]);
            echo json_encode(array('errno'=>0, 'data'=>$c, 'msg'=>json_encode($ids)));
        }
        else{
            echo json_encode(array('errno'=>2, 'msg'=>''));
        }
    
  
    }








    /**
     * Finds the User model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return User the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = User::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
